class ReportsController < ApplicationController
before_filter :login_required

  def new
    if params[:report_template_id]
      @report_template = ReportTemplate.find(params[:report_template_id])
    else
      @report_template = ReportTemplate.find(:first)
    end
    @report_templates = ReportTemplate.find(:all)
  end


  def show
    @report_template = ReportTemplate.find(params[:report_template_id])
    @report_templates = ReportTemplate.find(:all)
    @dates = params[:dates]
    error = false

    if params[:commit] == "Reset condition fields"
      render :action => "new"
    else

      conditions = ["ticket_template_id = (?)", @report_template.ticket_template.id]
      case @report_template.tickets_status
        when "open"
          conditions[0] += " AND group_id != 0"
        when "closed"
          conditions[0] += " AND group_id = 0"
      end

      if params[:dates]
        params[:dates].each_with_index {|date, i|
          date.tr_s!("./","-")
          if (date.to_date rescue false)
            conditions[0] += " AND #{@report_template.conditions[i][:field]} #{@report_template.conditions[i][:sign]} ?"
            conditions << date.to_date
          else
            error = true
            @dates = params[:dates]
          end
        }
      end
      if (!error)
        @tickets = Ticket.find(:all, :conditions => conditions, :order => @report_template.order, :limit => 200)
        flash[:notice] = ((tcount = Ticket.count(:conditions => conditions)) > 200) ? "Too many tickets (#{tcount}) conform condtitons. Only first 200 are shown" : nil
      else
        flash[:notice] = "Please fill in all dates correctly"
        render :action => "new"
      end
    end
  end

  def update_conditions
    @report_template = ReportTemplate.find(params[:report_template_id])
    render :partial => "conditions_fields"
  end

end
